package com.dy.yunying.biz.utils;

import com.sjda.framework.common.utils.MD5;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 *
 * 微信支付
 * @author zhuxm
 * @Date 2022-07-11 20:23:15
 */
public class WxPayUtils {

	private static final Logger logger = LoggerFactory.getLogger(WxPayUtils.class);
	/**
	 * 微信提现（企业付款）
	 */
	public static String payForUser(String mchAppid, String mchid, String nonceStr, String partnerTradeNo, String openId, String amount, String desc, String wxkey, String wxCertPath) throws Exception {
		Map<String, String> requestParams = new HashMap<>();
		requestParams.put("mch_appid", mchAppid);//申请商户号的appid或商户号绑定的appid-这里必须是小程序的appid
		requestParams.put("mchid", mchid);//宁德创游的商户号
		//requestParams.put("device_info", "WEB");//设备号
		requestParams.put("nonce_str", nonceStr);//随机字符串，长度要求在32位以内
		requestParams.put("partner_trade_no", partnerTradeNo);//商户订单号，需保持唯一性(只能是字母或者数字，不能包含有其它字符)
		requestParams.put("openid", openId);//随机字符串，长度要求在32位以内
		requestParams.put("check_name", "NO_CHECK");//NO_CHECK：不校验真实姓名 FORCE_CHECK：强校验真实姓名
		//requestParams.put("re_user_name", "");//收款用户真实姓名
		requestParams.put("amount", amount);//付款金额，单位为分
		requestParams.put("desc", desc);//付款备注，必填。注意：备注中的敏感词会被转成字符*
		requestParams.put("sign", createSign(requestParams, wxkey));
		return WeChatUtil.HttpsPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers", XMLUtils.GetMapToXML(requestParams), wxCertPath, mchid);
	}

	/**
	 * 生成签名
	 * @return
	 */
	private static String createSign(Map<String, String> map, String keys) {
		String sign = "";
		try {
			List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
			// 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
			infoIds.sort(new Comparator<Map.Entry<String, String>>() {
				public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
					return (o1.getKey()).compareTo(o2.getKey());
				}
			});
			// 构造签名键值对的格式
			StringBuilder sb = new StringBuilder();
			for (Map.Entry<String, String> item : infoIds) {
				if (item.getKey() != null || item.getKey() != "") {
					String key = item.getKey();
					String val = item.getValue();
					if (!(val == "" || val == null)) {
						sb.append(key + "=" + val + "&");
					}
				}
			}
			String msg = sb.substring(0, sb.length() - 1).toString() + "&key=" + keys;//sb.substring(0,sb.length()-1).toString()：截取最后一个&
			//String result = (sb.toString().length()-1)+keys;
			logger.info("================accsii排序===============" + msg);
			sign = MD5.sign(msg, "", "utf-8").toUpperCase();//MD5加密，toUpperCase()：大小写转换
			logger.info("================signMD5加密===============" + sign);
		} catch (Exception e) {
			return null;
		}
		return sign;
	}

}
